package com.wgl.yygh.serivice.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wgl.model.enums.AuthStatusEnum;
import com.wgl.model.user.Patient;
import com.wgl.model.user.UserInfo;
import com.wgl.model.vo.user.LoginVo;
import com.wgl.model.vo.user.UserAuthVo;
import com.wgl.model.vo.user.UserInfoQueryVo;
import com.wgl.yygh.dao.UserInfoMapper;
import com.wgl.yygh.exception.HospitalException;
import com.wgl.yygh.helper.JwtHelper;
import com.wgl.yygh.result.ResultCodeEnum;
import com.wgl.yygh.serivice.PatientService;
import com.wgl.yygh.serivice.UserInfoService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wgl
 * @version 1.0.0
 * @ClassName UserInfoServiceImpl.java
 * @Description TODO
 * @createTime 2022年02月09日 14:11:00
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private PatientService patientService;
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //获取手机号和验证码
        //判断手机号和验证码是否正确
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        //判断收键验证码和输入的验证码是否一致
        String codeRedis = (String) redisTemplate.opsForValue().get(phone);
        if (!code.equals(codeRedis)){
            throw new HospitalException(ResultCodeEnum.CODE_ERROR);

        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",phone);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        if (userInfo == null){
            //第一次登录 进行注册
            userInfo = new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            baseMapper.insert(userInfo);
        }
        if (userInfo.getStatus() == 0){
            throw new HospitalException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        Map<String,Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            //名称为空获取昵称
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)){
            //昵称为空获取手机号
            name = userInfo.getPhone();
        }
        map.put("name",name);
        map.put("token", JwtHelper.createToken(userInfo.getId(),name));
        //正确就判断是否为第一次登录
        //是第一次登录就注册用户 如果不是就查询数据并返回
        return map;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据id查询用户的信息
        UserInfo userInfo = baseMapper.selectById(userId);

        userInfo.setName(userAuthVo.getName()) ;//其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType()) ;
        userInfo.setCertificatesNo(userAuthVo. getCertificatesNo()) ;
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum. AUTH_RUN. getStatus() ) ;
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> page1, UserInfoQueryVo userInfoQueryVo) {
        //条为空则设置
        //用户名
        String name = userInfoQueryVo.getKeyword();
        //用户状态
        Integer status = userInfoQueryVo.getAuthStatus();
        //认证状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        //开始时间
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        //结束时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }

        if (!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }

        if (!StringUtils.isEmpty(authStatus)){
            wrapper.eq("auth_status",authStatus);
        }


        if (!StringUtils.isEmpty(createTimeBegin) ){
            wrapper.ge("create_timeBegin",createTimeBegin);
        }

        if (!StringUtils.isEmpty(createTimeEnd) ){
            wrapper.le("create_timeEnd",createTimeEnd);
        }

        Page<UserInfo> userInfoPage = baseMapper.selectPage(page1, wrapper);

        userInfoPage.getRecords().stream().forEach(userInfo -> {
            packageUserInfo(userInfo);
        });

        return userInfoPage;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if (status == 0 || status == 1){
            UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id",userId).set("status",status);
            baseMapper.update(null,updateWrapper);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map = new HashMap<>();
        //查询用户
        UserInfo userInfo = packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //查寻用户的就诊人信息
        List<Patient> list = patientService.fandAllUserId(userId);
        map.put("patientList",list);

        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if (authStatus == 2 || authStatus == -1){

            UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id",userId).set("auth_status",authStatus);
            baseMapper.update(null,updateWrapper);
        }

    }

    private UserInfo packageUserInfo(UserInfo userInfo) {
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));

        //处理用户状态
        String s = userInfo.getStatus() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString",s);

        return userInfo;
    }


}
